<?php
/** @noinspection ALL */

declare(strict_types=1);

namespace App\Resource\Service;

use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Resource\Model\CookbookGoodsModel;
use App\Resource\Model\CookbookModel;
use App\Resource\Model\GoodsModel;
use App\Social\Model\CollectModel;
use Hyperf\Di\Annotation\Inject;

class CookbookService extends BaseService
{

    const COLLECT = 1;
    /**
     * @param array $where
     * @param int $perPage
     * @param array|string[] $field
     *
     * @return array
     */
    public function getList(array $where, int $perPage = 15, array $field = ['*'])
    {
        $query = CookbookModel::query();
        !empty($where['title'])
        && $query->whereRaw('INSTR(title, ?) > 0', [$where['title']]);
        if (isset($where['status']) && $where['status'] != '') {
            $query->where('status', $where['status']);
        }
        $isTaxonomy = $where['isTaxonomy'] ?? 0;
        if ($isTaxonomy == 1) {
            $list = $query->orderBy('sort', 'desc')
                ->paginate($perPage, ['id', 'title']);

            return ['code' => ErrorCode::SUCCESS, 'data' => $list];
        }
        $list = $query->orderBy('sort', 'desc')->paginate($perPage, $field);
        if (!$list) {
            return ['code' => ErrorCode::SUCCESS, 'data' => []];
        }
        foreach ($list as $key => $val) {
            $main_materials = explode(',', $val['main_materials']);
            $second_materials = explode(',', $val['second_materials']);
            $matching_materials = explode(',', $val['matching_materials']);
            $list[$key]['main_materials'] = implode(',',
                GoodsModel::query()->whereIn('id', $main_materials)
                    ->pluck('title')->toArray());
            $list[$key]['second_materials'] = implode(',',
                GoodsModel::query()->whereIn('id', $second_materials)
                    ->pluck('title')->toArray());
            $list[$key]['matching_materials'] = implode(',',
                GoodsModel::query()->whereIn('id', $matching_materials)
                    ->pluck('title')->toArray());
        }

        return ['code' => ErrorCode::SUCCESS, 'data' => $list];
    }

    /**
     * @param int $id
     * @param array|string[] $field
     *
     * @return array
     */
    public function getInfoById(int $id, array $field = ['*'])
    {
        $res = CookbookModel::query()->where('id', $id)->select($field)->first();
        if (!$res) {
            return ['code' => ErrorCode::NOT_EXIST];
        }
        $main_materials = explode(',', $res['main_materials']);
        $second_materials = explode(',', $res['second_materials']);
        $matching_materials = explode(',', $res['matching_materials']);

        //---------------------------测试-----------------------------
        $arr = [];
        $arr['main_materials'] = $main_materials;
        $arr['second_materials'] = $second_materials;
        $arr['matching_materials'] = $matching_materials;

        $goodsId = [];
        $num = 0;
        //获取所有商品的 ID
        foreach ($arr as $key => $val) {
            foreach ($val as $k => $v) {
                $goodsId[$num] = $v;
                $num++;
            }
        }
        $goodsInfo = GoodsModel::query()
            ->from('store_goods as goods')
            ->leftJoin('store_goods_list as list', 'goods.id', '=', 'list.goods_id')
            ->leftJoin('store_goods_cate as cate', 'goods.cate_id', '=', 'cate.id')
            ->select([
                'goods.id',
                'goods.logo',
                'cate.title as category',
                'goods.title',
                'list.goods_spec',
                'goods.member_goods',
                'list.price_selling',
            ])
            ->whereIn('goods.id', $goodsId)
            ->get()
            ->toArray();
        $goodsInfo = array_column($goodsInfo, null, 'id');
        $foodsInfo = [];
        foreach ($arr as $key => $val) {
            foreach ($val as $k => $v) {
                $foodsInfo[$key][$k] = $goodsInfo[$v];
            }
        }
        $res['main_materials'] = $foodsInfo['main_materials'];
        $res['second_materials'] = $foodsInfo['second_materials'];
        $res['matching_materials'] = $foodsInfo['matching_materials'];
        return ['code' => ErrorCode::SUCCESS, 'data' => $res];
    }


    /**
     * @param array $params
     *
     * @return array
     */
    public function add(array $params)
    {
        $res = CookbookModel::create([
            'title' => $params['title'],
            'take_time' => $params['take_time'],
            'difficulty_level' => $params['difficulty_level'],
            'delicious_level' => $params['delicious_level'],
            'detailed_list' => $params['detailed_list'],
            'image' => $params['image'],
            'rotation_image' => $params['rotation_image'],
            'detail' => $params['detail'],
            'main_materials' => $params['main_materials'],
            'second_materials' => $params['second_materials'],
            'matching_materials' => $params['matching_materials'],
            'status' => $params['status'] ?? 0,
        ]);
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => [], 'info' => ['target_id' => $res -> id]];
        }

        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param array $params
     *
     * @return array
     */
    public function update(array $params)
    {
        $res = CookbookModel::query()->where(['id' => $params['id']])->update([
            'title' => $params['title'],
            'take_time' => $params['take_time'],
            'difficulty_level' => $params['difficulty_level'],
            'delicious_level' => $params['delicious_level'],
            'detailed_list' => $params['detailed_list'],
            'image' => $params['image'],
            'rotation_image' => $params['rotation_image'],
            'detail' => $params['detail'],
            'main_materials' => $params['main_materials'],
            'second_materials' => $params['second_materials'],
            'matching_materials' => $params['matching_materials'],
            'status' => $params['status'] ?? 0,
        ]);

        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $params['id']]];
        }

        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param string $id
     *
     * @return array
     */
    public function delete(string $id)
    {
        $idArr = explode(',', $id);
        $wantNum = count($idArr);
        $actually = CookbookModel::whereIn('id', $idArr)->where('status', 0)
            ->count('id');
        if ($wantNum > $actually) {
            return ['code' => ErrorCode::COOKBOOK_DELETE];
        }
        $res = CookbookModel::whereIn('id', $idArr)->delete();
        // 删除商品对应的该菜谱
        CookbookGoodsModel::query()->whereIn('cookbook_id', $idArr)->delete();
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['remarks' => '菜谱ID:'.$id]];
        }

        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param int $id
     * @param int $sort
     *
     * @return array
     */
    public function editSort(int $id, int $sort)
    {
        $res = CookbookModel::query()->where('id', $id)
            ->update(['sort' => $sort]);
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $id, 'remarks' => '修改排序为:'.$sort]];
        }

        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param int $cookbook
     *
     * @return array
     */
    public function getGoodsInCookbook(int $cookbook)
    {
        $mainMmaterials = CookbookModel::query()->where('id', $cookbook)
            ->value('main_materials');
        if (!$mainMmaterials) {
            return ['code' => ErrorCode::NOT_EXIST];
        }
        $mainMmaterials = explode(',', $mainMmaterials);
        $res = GoodsModel::query()->whereIn('id', $mainMmaterials)
            ->select(['id', 'title'])->get()->toArray();
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res];
        }

        return ['code' => ErrorCode::NOT_IN_FORCE];
    }
    /**
     * @param array $where
     * @param int $perPage
     * @param array|string[] $field
     * @return array
     */
    public function getCookBookList(array $where, int $perPage = 15, array $field = ['*'])
    {
        $query = CookbookModel::query();
        !empty($where['title'])
        && $query->whereRaw('INSTR(title, ?) > 0', [$where['title']]);
        $CookBookList = $query->where('status', 1)->orderBy('sort', 'desc')->paginate($perPage, $field);
        foreach ($CookBookList as $key => $val) {
            $CookBookList[$key]['collection_type'] = 0;
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => $CookBookList];
    }

    /**
     * @param int $mid
     * @param int $cook_id
     * @param int $shop_id
     * @param array $field
     * @return array
     */
    public function getCookBookInfo(int $mid, int $cook_id, int $shop_id, array $field = ['*'])
    {
        $res = CookbookModel::query()->where('id', $cook_id)->select($field)
            ->first();
        if (!$res) {
            return ['code' => ErrorCode::NOT_EXIST];
        }
        $main_materials = explode(',', $res['main_materials']);
        $second_materials = explode(',', $res['second_materials']);
        $matching_materials = explode(',', $res['matching_materials']);
        $res['main_materials'] = GoodsService::getGoodsInfoData($shop_id, $main_materials);
        $res['second_materials'] = GoodsService::getGoodsInfoData($shop_id, $second_materials);
        $res['matching_materials'] = GoodsService::getGoodsInfoData($shop_id, $matching_materials);
        $res['collection'] = CollectModel::query()->where(['mid' => $mid])->count();
        //查询当前菜谱是否收藏
        $is_collect = CollectModel::query()->where(['mid' => $mid, 'entity_id' => $cook_id, 'type' => 1])->exists();
        if ($is_collect) {
            $res['collection_type'] = 1;
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => $res];
    }

    /**
     * @param $where
     * @param $perPage
     * @return \Hyperf\Contract\LengthAwarePaginatorInterface
     */
    public function cookbookSimple($where, $perPage)
    {
        $query = CollectModel::query();
        $query->where('mid', $where['mid']);
        $query->where('type', $where['type']);

        $list = $query
            ->join('hf_cookbook as cookbook', 'hf_collect.entity_id', '=', 'cookbook.id')
            ->when($where['title'] ?? 0, function ($query, $title) {
                return $query->where('cookbook.title', 'LIKE', '%' . $title . '%');
            })
            ->select(['hf_collect.type','cookbook.id','cookbook.image', 'cookbook.title', 'cookbook.difficulty_level', 'cookbook.delicious_level', 'cookbook.take_time'])
            ->latest('entity_id')
            ->paginate($perPage);
        return $list;
    }

}
